package com.ai.plug.core.register.complete;

import com.ai.plug.core.annotation.McpCompleteScan;
import com.ai.plug.core.context.complete.ICompleteContext;
import com.ai.plug.core.utils.CustomToolUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author han
 * @time 2025/6/16 17:07
 *
 */

public class McpCompleteScanRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
    /**
     * 注册bean的实例
     */
    private static int index = 0;
    private ICompleteContext completeContext;
    private BeanFactory beanFactory;
    public McpCompleteScanRegistrar() {
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
    @Override
    /**
     * 根据导入类的元数据注册 Bean 定义
     * 
     * @param importingClassMetadata 导入类的元数据
     * @param registry Bean定义注册器
     */
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 获取 @McpCompleteScan 注解的属性值，用于后续的Bean定义注册
        // 通过AnnotationMetadata获取指定注解（McpCompleteScan）的属性信息
        // getAnnotationAttributes返回的是一个Map，其中包含了注解的所有属性值
        // 使用AnnotationAttributes.fromMap()方法将Map转换为AnnotationAttributes对象，便于后续处理
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                importingClassMetadata.getAnnotationAttributes(McpCompleteScan.class.getName())
        );

        // 如果存在注解属性，则根据这些属性注册Bean定义
        if (attributes != null) {
            registerBeanDefinitions(importingClassMetadata, attributes, registry);
        }
    }
    /**
     * 根据注解元数据和属性注册Bean定义
     * 
     * @param importingClassMetadata 导入类的注解元数据
     * @param attributes 注解属性
     * @param registry Bean定义注册器
     */
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, AnnotationAttributes attributes, BeanDefinitionRegistry registry) {
        // 从Bean工厂中获取ICompleteContext实例，用于后续的Bean定义配置
        this.completeContext = beanFactory.getBean(ICompleteContext.class);
        
        // 创建McpCompleteScanConfigurer的Bean定义构建器
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(McpCompleteScanConfigurer.class);

        // 获取basePackages属性值，如果未设置则使用默认包路径
        AnnotationAttributes[] basePackages = attributes.getAnnotationArray("basePackages");
        if (!CollectionUtils.isEmpty(List.of(basePackages))) {
            // 如果设置了basePackages，则使用配置的包路径
            builder.addPropertyValue("basePackages", basePackages);
        } else {
            // 如果未设置basePackages，则使用默认包路径（导入类所在的包）
            builder.addPropertyValue("basePackages", getDefaultBasePackage(importingClassMetadata));
        }

        // 获取excludeFilters属性值并设置到Bean定义中
        AnnotationAttributes[] excludeFilters = attributes.getAnnotationArray("excludeFilters");
        if (!CollectionUtils.isEmpty(List.of(basePackages))) {
            // 如果设置了excludeFilters，则添加到Bean定义中
            builder.addPropertyValue("excludeFilters", excludeFilters);
        }

        // 获取includeFilters属性值并设置到Bean定义中
        AnnotationAttributes[] includeFilters = attributes.getAnnotationArray("includeFilters");
        if (!CollectionUtils.isEmpty(List.of(includeFilters))) {
            // 如果设置了includeFilters，则添加到Bean定义中
            builder.addPropertyValue("includeFilters", includeFilters);
        }
        
        // 将completeContext设置到Bean定义中
        builder.addPropertyValue("completeContext", this.completeContext);

        // 设置Bean的角色为2（ROLE_SUPPORT）
        builder.setRole(2);
        
        // 注册Bean定义到注册器中，使用生成的Bean名称
        registry.registerBeanDefinition(generateBaseBeanName(importingClassMetadata, index++), builder.getBeanDefinition());
    }

    private static String generateBaseBeanName(AnnotationMetadata importingClassMetadata, int index) {
        return CustomToolUtil.generateBaseBeanName(importingClassMetadata, index);
    }
    private static String getDefaultBasePackage(AnnotationMetadata importingClassMetadata) {
        return ClassUtils.getPackageName(importingClassMetadata.getClassName());
    }




    /**
     * 给McpCompleteScans用
     */
    public static class RepeatingRegistrar extends McpCompleteScanRegistrar {

        public RepeatingRegistrar() {
        }

        @Override
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            AnnotationAttributes attributes = (AnnotationAttributes) importingClassMetadata.getAnnotationAttributes(McpCompleteScan.class.getName());
            AnnotationAttributes[] annotations = attributes.getAnnotationArray("value");
            for (AnnotationAttributes annotation : annotations) {
                this.registerBeanDefinitions(importingClassMetadata, annotation, registry);
            }
        }

    }

}
